<template>
  <BaseDialog
    :title="title"
    :handleCancel="handleCancel"
    :handleOk="handleOk"
    width="1000px"
    v-model:dialogVisible="props.dialogVisible"
    :footer="true"
  >
    <div class="dialog__body">
      <div class="left">
        <div class="use_titile">选择台区</div>
        <el-form
          ref="ruleFormRef"
          :model="searchParams"
          style="padding: 16px 16px 0 16px"
          :inline="true"
          label-width="0px"
        >
          <el-form-item>
            <el-input
              style="width: 160px"
              v-model="searchParams.areaCode"
              placeholder="请输入台区编号"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              style="width: 160px"
              v-model="searchParams.areaName"
              placeholder="请输入台区名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <selectPage
              :item="powerItem"
              v-model="searchParams.powerId"
              @update:modelValue="changePower"
            />
          </el-form-item>
          <el-form-item>
            <selectPage
              :item="lineItem"
              v-model="searchParams.lineId"
              :search="lineSearch"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon>
                <Search />
              </el-icon>
              查询
            </el-button>
            <el-button @click="resetForm">
              <el-icon>
                <RefreshLeft />
              </el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>

        <el-table
          border
          ref="multipleTableRef"
          v-loading="loading"
          element-loading-text="加载中..."
          :data="list"
          height="320px"
          @select="handleSelectionChange"
          @select-all="selectAll"
          :row-key="getRowKeys"
        >
          <el-table-column
            :reserve-selection="true"
            type="selection"
            width="55"
          />
          <el-table-column prop="areaCode" label="台区编号" />
          <el-table-column prop="areaName" label="台区名称"> </el-table-column>
          <el-table-column
            prop="address"
            label="供电单位"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ getPowerName(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="供电线路"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ getLineName(scope.row) }}
            </template>
          </el-table-column>
        </el-table>

        <Pages
          style="margin-top: 10px"
          v-model:page="page"
          :small="true"
          :getTableData="getTableData"
        ></Pages>
      </div>
      <div class="right">
        <div class="use_titile">已选择</div>
        <el-scrollbar class="scrollBox" style="height: 400px">
          <div
            v-for="(n, i) in selectList"
            :key="i"
            class="selectList"
            style="margin-top: 5px"
          >
            <el-tag type="info" closable @close="handleClose(n)">
              {{ n.areaName }}
            </el-tag>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </BaseDialog>
</template>

<script setup lang="ts">
import { basicConfigService } from "@/api/basicConfig";

import { commonService } from "@/api/common";
import { ElTable } from "element-plus";
import { powerService } from "@/api/power";
import { lineService } from "@/api/line";
import selectPage from "../selectPage.vue";

const props = defineProps({
  dialogVisible: {
    type: Boolean,
  },
  item: {
    type: Object,
  },
  handleSearch: {
    type: Function,
  },
  showManager: {
    type: Boolean,
    default: true,
  },
  title: {
    type: String,
    default: "选择台区",
  },
  type: {
    type: Number,
  },
  selecedList: {
    type: Array,
  },
});
watch(
  () => [...props.selecedList],
  () => {
    selectList.value = [...props.selecedList];
  }
);
const searchParams = ref({
  areaCode: "",
  areaName: "",
  powerId: "",
  lineId: "",
});
const powerItem = ref({
  name: "供电单位",
  key: "powerId",
  funName: "getByAreaQueryByPower",
  option: {
    name: "powerName",
    value: "powerId",
  },
});
const lineItem = ref({
  name: "供电线路",
  key: "lineId",
  funName: "getByAreaQueryByLine",
  option: {
    name: "lineName",
    value: "lineId",
  },
});
const lineSearch = ref({
  powerId: searchParams.value.powerId,
});
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
let list = reactive([]);
const checkAll = ref(false);
const selectList = ref([...props.selecedList]);
const handleSelectionChange = (rows, row) => {
  console.log(rows, row);
  if (rows.findIndex((e) => e.areaId === row.areaId) > -1) {
    selectList.value.push(row);
  } else {
    let key = "areaId";
    selectList.value = selectList.value.filter((v) => v[key] != row[key]);
  }
};
const selectAll = (rows) => {
  const key = "areaId";
  if (rows.length > 0) {
    const selectSet = selectList.value.map((item) => item[key]);
    list.forEach((item) => {
      if (!selectSet.includes(item[key])) selectList.value.push(item);
    });
  } else {
    list.forEach((item) => {
      for (let index = 0; index < selectList.value.length; index++) {
        if (selectList.value[index][key] == item[key]) {
          selectList.value.splice(index, 1);
        }
      }
    });
  }
};
const handleClose = (e) => {
  selectList.value = selectList.value.filter((x) => x.areaId !== e.areaId);
  filterList();
};

const activeName = ref(1);
const lineIdList = ref([]);
const powerSupplyIdList = ref([]);

const loading = ref(false);

const page = reactive({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});

const getTableData = async (e) => {
  let data = {
    data: {
      ...searchParams.value,
    },
    pageSize: page.pageSize,
    pageNumber: page.currentPage,
  };
  list = [];
  loading.value = true;
  try {
    let res;
    res = await basicConfigService.pageListGridAreaResDto(data);
    list = res.data.content;
    page.total = res.data.total * 1;
    // filterList(iSarea.value ? 'areaId' : 'communityId')
    filterList();
    loading.value = false;
  } catch (error) {
    loading.value = false;
    list = [];
  }
};
const filterList = () => {
  const key = "areaId";
  nextTick(() => {
    multipleTableRef.value!.clearSelection();
  });
  list.forEach((row) => {
    if (selectList.value.findIndex((v) => row[key] == v[key]) > -1) {
      console.log(1000);
      nextTick(() => {
        multipleTableRef.value!.toggleRowSelection(row, true);
      });
    }
  });
};
const handleSearch = () => {
  page.currentPage = 1;
  getTableData(activeName.value);
};

const emit = defineEmits(["update:dialogVisible", "update:selecedList"]);
const handleOk = (data) => {
  emit("update:selecedList", selectList.value);
  handleCancel();
};

const handleCancel = () => {
  emit("update:dialogVisible", false);
};
const optionsMange = ref([]);
const getAllManager = () => {
  basicConfigService.getAllManager({ data: {} }).then((res) => {
    optionsMange.value = res.data.map((n) => {
      return {
        label: n.managerName,
        value: n.managerId,
      };
    });
  });
};
onMounted(() => {
  getTableData(activeName.value);

  //   getPowerList();
  getAllManager();
});
const resetForm = () => {
  searchParams.value = {
    areaCode: "",
    areaName: "",
    powerId: "",
    lineId: "",
  };
  getLineList();
  getTableData(activeName.value);
  lineSearch.value.powerId = "";
};
// const getPowerList = () => {
//   basicConfigService.getByAreaQueryDto({ data: {} }).then((res) => {
//     powerSupplyIdList.value = res.data.map((n) => {
//       return {
//         label: n.powerName,
//         value: n.powerId,
//       };
//     });
//     lineIdList.value = res.data.map((n) => {
//       return {
//         label: n.lineName,
//         value: n.lineId,
//       };
//     });
//   });
// };
const getLineList = () => {
  basicConfigService
    .getByAreaQueryDto({ data: { powerId: searchParams.value.powerId } })
    .then((res) => {
      lineIdList.value = res.data.map((n) => {
        return {
          label: n.lineName,
          value: n.lineId,
        };
      });
    });
};
const changePower = (val: any) => {
  lineSearch.value.powerId = val;
  searchParams.value.lineId = "";
};
const getPowerName = (row) => {
  let powerNames = row.areaPowerLineResDtoList?.map((n) => n.powerName);
  if (powerNames.length > 0) {
    return [...new Set(powerNames)].join("、");
  }
  return "";
};
const getLineName = (row) => {
  let lineNames = row.areaPowerLineResDtoList?.map((n) => n.lineName);
  if (lineNames.length > 0) {
    return [...new Set(lineNames)].join("、");
  }
  return "";
};
const getRowKeys = (row) => {
  return row.areaId;
};
</script>
<style lang="scss" scoped>
.dialog__body {
  display: flex;

  .left {
    width: 650px;
  }

  .right {
    flex: 1;
    width: 0;
    border-left: 1px solid #ccc;
    padding-left: 10px;
  }
}
</style>
